package com.singing.dao;

import com.singing.model.Admin;
import com.singing.util.DbUtil;

import java.sql.*;

public class AdminDao {


    //根据账号查询用户
    public Admin selectByAccount(String account) {
        Connection connection = DbUtil.getConnection();
        PreparedStatement ps = null;
        ResultSet resultSet = null;
        try {
            ps = connection.prepareStatement("select * from admin where account=?");

            ps.setString(1, account);
            resultSet = ps.executeQuery();
            Admin admin = null;
            if (resultSet.next()) {
                admin = new Admin();
                admin.setId(resultSet.getInt("id"));
                admin.setName(resultSet.getString("name"));
                admin.setPassword(resultSet.getString("password"));
                admin.setAccount(resultSet.getString("account"));
            }
            return admin;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DbUtil.closeResource(connection, ps, resultSet);
        }
        return null;
    }


    // 添加管理员用户
    public int insert(Admin admin) {

        Connection connection = DbUtil.getConnection();
        PreparedStatement ps = null;
        try {
            ps = connection.prepareStatement(
                    "insert into admin(name,password,account) values(?,?,?)",
                    Statement.RETURN_GENERATED_KEYS);
            ps.setString(1, admin.getName());
            ps.setString(2, admin.getPassword());
            ps.setString(3, admin.getAccount());
            int result = ps.executeUpdate();

            try (ResultSet rs = ps.getGeneratedKeys()) {
                if (rs.next()) {
                    int generatedId = rs.getInt(1);
                    admin.setId(generatedId);
                }
            }
            return result;
        } catch (Exception e) {

            e.printStackTrace();
        } finally {

            DbUtil.closeResource(connection, ps);
        }
        return 0;
    }
}
